﻿#include "TIScriptWidget.h"
#include "ui_TIScriptWidget.h"

#include "services/Task/TlvCmdTask.h"
#include "services/Task/TlvCodeTask.h"
#include "components/Toast/Toast.h"

#include <QFileDialog>


TIScriptWidget::TIScriptWidget(QWidget *parent)
    : QDockWidget(parent)
    , ui(new Ui::TIScriptWidget)
{
    ui->setupUi(this);
    setWindowTitle(tr("TI Script"));

    ui->btnRun->setOnIcon(QIcon(":/imgs/stop.png"));

    TlvCodeTask* task = TlvCodeTask::instance();
    connect(task, &TlvCodeTask::taskFinished, this, [=](){
        ui->btnRun->setIconStatus(false);
    });
}

TIScriptWidget::~TIScriptWidget()
{
    delete ui;
}

void TIScriptWidget::on_btnBrowse_clicked()
{
    QString pyFilePath = QFileDialog::getOpenFileName(this, tr("Select TI Script File"), "", tr("python file (*.py)"));
    if (pyFilePath.isEmpty()) return;

    QFile f(pyFilePath);
    if (!f.open(QIODevice::ReadOnly)) return;
    ui->wEditor->setText(f.readAll());
    f.close();

    ui->leScriptPath->setText(pyFilePath);
}


void TIScriptWidget::on_btnRun_clicked()
{
    TlvCodeTask* task = TlvCodeTask::instance();
    IconButton* btn = ui->btnRun;

    if (btn->isOn() && task->isRunning()) {  // 这是判断运行的任务是否是当前选择的任务
        task->stop();
        btn->setIconStatus(false);
        Toast::info( ITask::INFO_TASK_STOPPED(task->taskName()) );
        return;
    }
    if (task->isRunning()) {  // 其它Code任务正在运行
        Toast::warning( ITask::WARN_TASK_IS_RUNNING(task->taskName()) );
        return;
    }
    if (TlvCmdTask::instance()->isRunning()) {  // Cmd任务正在运行
        Toast::warning( ITask::WARN_TASK_IS_RUNNING(TlvCmdTask::instance()->taskName()) );
        return;
    }
    btn->setIconStatus(true);
    task->setTaskName(QString("Code.%1").arg(windowTitle()));
    task->setCode(ui->wEditor->code());
    task->setCodeType(TlvCodeTask::Python);
    task->start();
}
